package com.sgb.kjwl.view.ui.activity.packers;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityPacksSearchBinding;
import com.sgb.kjwl.di.packers.DaggerPackersComponent;
import com.sgb.kjwl.di.packers.PackersModule;
import com.sgb.kjwl.view.ui.adapter.packers.SearchFlowLayoutAdapter;
import com.sgb.kjwl.view.ui.fragment.packers.FindJobSearchFragment;
import com.sgb.kjwl.view.ui.fragment.packers.FindPackersSearchFragment;
import com.sgb.kjwl.view.ui.fragment.packers.FindWorkerSearchFragment;
import com.sgb.kjwl.view.ui.fragment.packers.PackersEmploymentSearchFragment;
import com.sgb.kjwl.view.ui.fragment.packers.QuotePriceSearchFragment;
import com.sgb.kjwl.view.widget.MyItemDecoration;
import com.sgb.kjwl.viewmodel.packers.PackersSearchModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.recyclerview.FlowLayoutManager;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.adapter.SlidingFragmentPagerAdapter;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 *
 * @author WYJ
 * @date 2020/9/8
 * description:搜索
 */
public class PackersSearchActivity extends AppActivity {

    @Inject
    PackersSearchModel mModel;
    private ActivityPacksSearchBinding mBind;
    ArrayList<Fragment> mFragments;

    private final String[] mTitles = {"工程工队", "工种报价", "劳务分包", "临时用工", "找工人"};
    private boolean isInitialize = false;

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, PackersSearchActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPackersComponent.builder().appComponent(appComponent).packersModule(new PackersModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        mBind = DataBindingUtil.setContentView(this, R.layout.activity_packs_search);
        mBind.setViewModel(mModel);
        mBind.ivBack.setOnClickListener(this);
        mBind.tvSearch.setOnClickListener(this);
        mBind.ivDeleteHistory.setOnClickListener(this);
        mBind.etView.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                mBind.searchLayout.setVisibility(View.VISIBLE);
                mBind.emptyView.setVisibility(View.GONE);
            }
        });
        initHistory(mModel.getHistorySearchList());
        mModel.getTeamHotKeySearch();
    }

    private void initHistory(List<String> historySearchList) {
        if (historySearchList == null) {
            mBind.linHistory.setVisibility(View.GONE);
        } else {
            mBind.linHistory.setVisibility(View.VISIBLE);
        }
        SearchFlowLayoutAdapter mHisAdapter = new SearchFlowLayoutAdapter(this, historySearchList);
        mBind.rvHistory.setLayoutManager(new FlowLayoutManager());
        mBind.rvHistory.addItemDecoration(new MyItemDecoration());
        mBind.rvHistory.setAdapter(mHisAdapter);
        mHisAdapter.setOnItemClick(new AdapterOnItemClick<String>() {
            @Override
            public void onItemClick(String s, int position) {
                updateSearchInfo(s);
            }
        });
    }

    public void initHot(List<String> data) {
        SearchFlowLayoutAdapter mHotAdapter = new SearchFlowLayoutAdapter(this, data);
        mBind.rvHot.setLayoutManager(new FlowLayoutManager());
        mBind.rvHot.addItemDecoration(new MyItemDecoration());
        mBind.rvHot.setAdapter(mHotAdapter);
        mHotAdapter.setOnItemClick(new AdapterOnItemClick<String>() {
            @Override
            public void onItemClick(String s, int position) {
                updateSearchInfo(s);
            }
        });
    }

    private void updateSearchInfo(String s) {
        hideSoftKeyboard(mBind.etView, getActivity());
        mBind.searchLayout.setVisibility(View.GONE);
        mBind.emptyView.setVisibility(View.GONE);
        mBind.etView.setText(s);
        mModel.setShardHistorySearch(s);
        if (mFragments == null || mFragments.size() == 0) {
            if (!isInitialize) {
                initTabs();
                isInitialize = true;
            } else {
                ((FindPackersSearchFragment) (mPagerAdapter.getItem(0))).refreshKeywordRequest();
                ((QuotePriceSearchFragment) (mPagerAdapter.getItem(1))).refreshKeywordRequest();
                ((FindJobSearchFragment) (mPagerAdapter.getItem(2))).refreshKeywordRequest();
                ((PackersEmploymentSearchFragment) (mPagerAdapter.getItem(3))).refreshKeywordRequest();
                ((FindWorkerSearchFragment) (mPagerAdapter.getItem(4))).refreshKeywordRequest();
            }
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            onBackPressed();
        } else if (id == R.id.tv_search) {
            String content = mBind.etView.getText().toString();
            mModel.setShardHistorySearch(content);
            hideSoftKeyboard(mBind.etView, this);
            if (!TextUtils.isEmpty(content)) {
                mBind.searchLayout.setVisibility(View.GONE);
                mBind.emptyView.setVisibility(View.GONE);
                if (!isInitialize) {
                    initTabs();
                    isInitialize = true;
                } else {
                    ((FindPackersSearchFragment) (mPagerAdapter.getItem(0))).refreshKeywordRequest();
                    ((QuotePriceSearchFragment) (mPagerAdapter.getItem(1))).refreshKeywordRequest();
                    ((FindJobSearchFragment) (mPagerAdapter.getItem(2))).refreshKeywordRequest();
                    ((PackersEmploymentSearchFragment) (mPagerAdapter.getItem(3))).refreshKeywordRequest();
                    ((FindWorkerSearchFragment) (mPagerAdapter.getItem(4))).refreshKeywordRequest();
                }
            }
        } else if (id == R.id.iv_delete_history) {
            if (mModel.clearHistorySearchData()) {
                initHistory(null);
            }
        }
    }

    private SlidingFragmentPagerAdapter mPagerAdapter;

    private void initTabs(){
        mFragments = new ArrayList<>();
        mFragments.add(FindPackersSearchFragment.newInstance());
        mFragments.add(QuotePriceSearchFragment.newInstance());
        mFragments.add(FindJobSearchFragment.newInstance());
        mFragments.add(PackersEmploymentSearchFragment.newInstance());
        mFragments.add(FindWorkerSearchFragment.newInstance());
        mPagerAdapter = new SlidingFragmentPagerAdapter(getSupportFragmentManager(), mFragments, mTitles);
        mBind.vp.setOffscreenPageLimit(mTitles.length);
        mBind.vp.setAdapter(mPagerAdapter);
        mBind.tabLayout.setupWithViewPager(mBind.vp);
        DialogHelper.dismissProgressDialog();
        for (int i = 0; i < mTitles.length; i++) {
            mBind.tabLayout.getTabAt(i).setCustomView(R.layout.item_tablayout_view_1);
            TextView tv = mBind.tabLayout.getTabAt(i).getCustomView().findViewById(R.id.tv_tab_item);
            tv.setText(mTitles[i]);
            if (i == 0) {
                tv.setTextColor(ContextCompat.getColor(PackersSearchActivity.this, R.color.color_FFFFFF));
                tv.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
            }
        }
        mBind.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                TextView tv = tab.getCustomView().findViewById(R.id.tv_tab_item);
                tv.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));//加粗
                tv.setTextColor(ContextCompat.getColor(PackersSearchActivity.this, R.color.color_FFFFFF));
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
                tv.invalidate();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                TextView tv = tab.getCustomView().findViewById(R.id.tv_tab_item);
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
                tv.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                tv.setTextColor(ContextCompat.getColor(PackersSearchActivity.this, R.color.color_C0C4CC));
                tv.invalidate();
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    public void showEmpty() {
        mBind.emptyView.setVisibility(View.VISIBLE);
        DialogHelper.dismissProgressDialog();
    }

    public void hideSoftKeyboard(EditText editText, Context context) {
        if (editText != null && context != null) {
            InputMethodManager imm = (InputMethodManager) context
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        }
    }

    public String getEditContent(){
        return mBind.etView.getText().toString();
    }
}
